//
//  HCForgetViewController.m
//  HappyChildren
//
//  Created by WillyZhao on 2017/3/2.
//  Copyright © 2017年 WillyZhao. All rights reserved.
//

#import "HCForgetViewController.h"

@interface HCForgetViewController () {
    UITextField *phoneField_;
    UITextField *pwdField_;
    UIButton *button_;
    UITextField *codeField_;
    UITextField *repasswordField_;
    UIButton *getCodeButton_;
    NSString *codeString_;
}

@end

@implementation HCForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.textTitle = @"忘记密码";
    
    UIView *forgetView = [[[NSBundle mainBundle] loadNibNamed:@"andnoadnoiaonis" owner:self options:nil]firstObject];
    forgetView.frame = CGRectMake(0, 0, self.centerView.frame.size.width, self.centerView.frame.size.height);
    forgetView.backgroundColor = YBKRGBCOLOR(241, 241, 241, 1);
    [self.centerView addSubview:forgetView];
    
    UIView *lineView = (UIView *)[forgetView viewWithTag:104];
    lineView.backgroundColor = forgetView.backgroundColor;
    
    UIView *lineView1 = (UIView *)[forgetView viewWithTag:108];
    lineView1.backgroundColor = forgetView.backgroundColor;
    
    UIView *lineView2 = (UIView *)[forgetView viewWithTag:109];
    lineView2.backgroundColor = forgetView.backgroundColor;
    
    phoneField_ = (UITextField *)[forgetView viewWithTag:101];
    pwdField_ = (UITextField *)[forgetView viewWithTag:102];
    pwdField_.secureTextEntry = YES;
    button_ = (UIButton *)[forgetView viewWithTag:103];
    button_.backgroundColor = YBKRGBCOLOR(240, 96, 96, 1);
    [button_ addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    codeField_ = (UITextField *)[forgetView viewWithTag:105];
    getCodeButton_ = (UIButton *)[forgetView viewWithTag:106];
    repasswordField_ = (UITextField *)[forgetView viewWithTag:107];
    getCodeButton_.backgroundColor = YBKRGBCOLOR(240, 96, 96, 1);
    [getCodeButton_ setTitle:@"获取验证码" forState:UIControlStateNormal];
    getCodeButton_.titleLabel.font = YBKSystemFont(YBKAdaptiveFont(12));
    [getCodeButton_ setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [getCodeButton_ addTarget:self action:@selector(getCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    self.dataRequest.delegate = self;
}

-(void)buttonAction:(UIButton *)btn {
    if ([PublicFunction checkTelNumber:phoneField_.text]) {
        //是手机号
        if ([codeString_ isEqualToString:codeField_.text]) {
            
            if ([pwdField_.text length]>16||[pwdField_.text length]<6) {
                
                [XHToast showBottomWithText:@"密码位数不正确"];
                return;
            }
            if (![pwdField_.text isEqualToString:repasswordField_.text]) {
                
                [XHToast showBottomWithText:@"两次密码不一致"];
                return;
            }
        }
        else {
        
            [XHToast showBottomWithText:@"请输入验证码"];
            return;
        }
    }else{
        //不是手机号
        [XHToast showBottomWithText:@"请输入正确手机号"];
        return;
    }
    //发起网络请求
    [self.dataRequest postHC_FoegetPWD:phoneField_.text andpwd:pwdField_.text];
}

//点击获取验证码
- (void)getCodeAction:(UIButton *)sender {

    if ([PublicFunction checkTelNumber:phoneField_.text]) {
        //是手机号
        [self theWayLessTimeButton:sender WithTime:60 AndTitle:@"验证码"];
        [self.dataRequest postHC_forgetPasswordGetCode:phoneField_.text];
        
    }else{
        //不是手机号
        [XHToast showBottomWithText:@"请输入正确手机号"];
    }
}

#pragma mark -- 倒计时按钮
-(void)theWayLessTimeButton:(UIButton *)button WithTime:(NSInteger)time AndTitle:(NSString *)title{
    //    UIButton *buttonLess = (UIButton *)button;
    button.titleLabel.numberOfLines = 0;
    __block int timeout= (int)time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 创建一个定时器(dispatch_source_t本质还是个OC对象,创建出来的对象需要强引用)
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 设置定时器的各种属性(几时开始任务，每隔多长时间执行一次)
    // GCD的时间参数，一般是纳秒(1秒 = 10的9次方纳秒)
    // 何时开始执行第一个任务
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)); //比当前时间晚1秒
    //    dispatch_time_t start = DISPATCH_TIME_NOW;// 当前时间执行
    uint64_t interval= 2.0 * NSEC_PER_SEC;
    dispatch_source_set_timer(self.timer, start, interval, 0); // NSEC_PER_SEC 纳秒
    // 设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        
        timeout--;
        //记好了刷新UI的时候一定要在主队列中刷新,就是主线程.
        dispatch_async(dispatch_get_main_queue(), ^{
            button.userInteractionEnabled=NO;
            [button setTitle:[NSString stringWithFormat:@"   %ds后重新获取   ",timeout] forState:UIControlStateNormal];
            if (timeout == 1) {
                
                [button setTitle:@"   获取验证码   " forState:UIControlStateNormal];
                button.userInteractionEnabled=YES;
                dispatch_cancel(self.timer);
                self.timer = nil;
            }
        });
        /*
         GCD的定时器要比NStimer的定时器要精确的多.
         */
    });
    // 启动定时器
    dispatch_resume(self.timer);
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

-(void)dataRequesterFinish:(DataRequester *)requester requesterWithType:(DataRequestType)aType receiveDictionary:(NSDictionary *)dictionary {
    
    
    if (aType == HC_FORGETPASSWORD_CHECK) {
        
        //获取验证码回调
        if ([dictionary[@"stat"] integerValue] == 200) {
            
            //获取验证码成功
            [XHToast showBottomWithText:@"获取验证码成功"];
            codeString_ = [NSString stringWithFormat:@"%@",dictionary[@"param"]];
        }
    }
    else {
    
        //修改密码回调
        if ([dictionary[@"stat"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改密码成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"修改密码失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }]];
            
            [self presentViewController:alert animated:YES completion:NULL];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
